﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using MySql.Data.MySqlClient;
using System.Net;

using VirtualShare;
using VirtualShare.Common;

namespace VirtualShare.Server
{
    class Client : Common.Client
    {
        Socket socket;

        NetworkStream clientStream;
        BinaryReader clientReader;
        BinaryWriter clientWriter;

        byte[] buffer = new byte[2];

        public Client(Socket socket)
        {
            this.socket = socket;
            ip = IPAddress.Parse(socket.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]);

            clientStream = new NetworkStream(socket);
            clientReader = new BinaryReader(clientStream);
            clientWriter = new BinaryWriter(clientStream);

            clientReader.ReadInt16();
            string user = clientReader.ReadString();
            string pass = clientReader.ReadString();

            foreach (Client client in Program.clients)
            {
                if (client.name == user)
                {
                    clientWriter.Write((short)PacketType.LoginFail);
                    return;
                }

            }

            MySqlCommand cmd = new MySqlCommand(String.Format("SELECT * FROM users WHERE user = '{0}' AND pass = '{1}'", user, pass), Program.mysql);
            MySqlDataReader reader = cmd.ExecuteReader();

            if (!reader.Read())
            {
                clientWriter.Write((short)PacketType.LoginFail);

                // TODO : On envoi la cause de l'échec
                reader.Close();
                return;
            }

            clientWriter.Write((short)PacketType.LoginConfirm);

            // On charge les données relatives au client
            id = reader.GetInt32("id");
            name = user; //reader.GetString("user");
            reader.Close();

            // On envoi les données au client
            SendClientInfo(this);

            foreach (Client client in Program.clients)
            {
                client.SendBuddyConnection(this);
                SendBuddyConnection(client);
            }

            Log.WriteLine(ConsoleColor.DarkGreen, "Connexion de {0}", name);

            clientStream.BeginRead(buffer, 0, 2, new AsyncCallback(onReceiveData), null);
        }

        // Evenements
        public void onReceiveData(IAsyncResult asyncResult)
        {
            if (!clientStream.DataAvailable)
            {
                Log.WriteLine(ConsoleColor.DarkRed, "Déconnexion de {0}", name);
                Program.clients.Remove(this);
                return;
            }

            clientStream.EndRead(asyncResult);
            switch ((PacketType)BitConverter.ToInt16(buffer, 0))
            {

            }
        }

        // Fonctions
        public void SendBuddyConnection(Client buddy)
        {
            clientWriter.Write((short)PacketType.BuddyConnection);
            SendClientInfo(buddy);
        }

        public void SendClientInfo(Client client)
        {
            clientWriter.Write(client.id);
            clientWriter.Write(client.name);
            clientWriter.Write(ip.GetAddressBytes());
        }
    }
}
